import { Button, Col, Input, InputNumber, Row } from "antd"
import { useEffect, useState } from "react"

import { DecimalCalculator as calc } from "../utils/math"

import "./style.css"

import { getFBA } from "../utils/getFBA"

function IndexPopup() {
  const saveLocalDataKey = "amazon-extension-dataForm"

  useEffect(() => {
    // 获取本地存储的数据
    const res = localStorage.getItem(saveLocalDataKey)
    if (res) {
      const obj = JSON.parse(res)
      setDataForm(obj)
    }
  }, [])

  const [dataForm, setDataForm] = useState({
    chang1: 0, // 英制
    chang2: 0, // 公制
    kuan1: 0, // 英制
    kuan2: 0,
    gao1: 0, // 英制
    gao2: 0,
    tijizhong1: 0,
    tijizhong2: 0,
    zhongOz: 0,
    zhongP: 0,
    zhongG: 0,
    caigou: 0,
    fba1: 0,
    fba2: 0,
    dingjia1: 0,
    dingjia2: 0,
    huilv: 7.2,
    toucheng: 0,
    guanggao: 0,
    guanggaolv: 10,
    tuihuo: 0,
    tuihuolv: 10,
    cangchu: 0,
    cangchulv: 1,
    yongjin: 0,
    yongjinlv: 15,
    maochengben: 0,
    maoli: 0,
    maolilv: 0,
    jingchengben: 0,
    jingli: 0,
    jinglilv: 0
  })
  useEffect(() => {
    // 保存到本地存储
    localStorage.setItem(saveLocalDataKey, JSON.stringify(dataForm))
  }, [dataForm])
  // 监听长宽高 计算体积重
  useEffect(() => {
    const { chang1, chang2, kuan1, kuan2, gao1, gao2 } = dataForm
    if (chang1 && chang2 && kuan1 && kuan2 && gao1 && gao2) {
      handleInputChange(
        "tijizhong1",
        calc.chain(chang1).multiply(kuan1).multiply(gao1).divide(133).round(2)
      )
      handleInputChange(
        "tijizhong2",
        calc.chain(chang2).multiply(kuan2).multiply(gao2).divide(5000).round(2)
      )
    }
  }, [
    dataForm.chang1,
    dataForm.chang2,
    dataForm.kuan1,
    dataForm.kuan2,
    dataForm.gao1,
    dataForm.gao2
  ])

  const lengthChangeUnit = 2.54 // 1英寸=2.54厘米

  // 处理单个字段变化
  const handleInputChange = (
    fieldName: keyof typeof dataForm,
    value: number
  ) => {
    switch (fieldName) {
      case "chang1":
        // 英寸变化，更新厘米
        setDataForm((prev) => ({
          ...prev,
          chang1: value,
          chang2: calc.multiply(value, lengthChangeUnit)
        }))
        break
      case "chang2":
        // 厘米变化，更新英寸
        setDataForm((prev) => ({
          ...prev,
          chang2: value,
          chang1: calc.divide(value, lengthChangeUnit)
        }))
        break
      case "kuan1":
        // 英寸变化，更新厘米
        setDataForm((prev) => ({
          ...prev,
          kuan1: value,
          kuan2: calc.multiply(value, lengthChangeUnit)
        }))
        break
      case "kuan2":
        // 厘米变化，更新英寸
        setDataForm((prev) => ({
          ...prev,
          kuan2: value,
          kuan1: calc.divide(value, lengthChangeUnit)
        }))
        break
      case "gao1":
        // 英寸变化，更新厘米
        setDataForm((prev) => ({
          ...prev,
          gao1: value,
          gao2: calc.multiply(value, lengthChangeUnit)
        }))
        break
      case "gao2":
        // 厘米变化，更新英寸
        setDataForm((prev) => ({
          ...prev,
          gao2: value,
          gao1: calc.divide(value, lengthChangeUnit)
        }))
        break
      case "zhongOz":
        // 盎司变化，更新磅和克
        setDataForm((prev) => ({
          ...prev,
          zhongOz: value,
          zhongP: calc.divide(value, 16), // 1磅=16盎司
          zhongG: calc.multiply(value, 28.3495) // 1盎司=28.3495克
        }))
        break
      case "zhongP":
        // 磅变化，更新盎司和克
        setDataForm((prev) => ({
          ...prev,
          zhongP: value,
          zhongOz: calc.multiply(value, 16), // 1磅=16盎司
          zhongG: calc.multiply(value, 453.592) // 1磅=453.592克
        }))
        break
      case "zhongG":
        // 克变化，更新盎司和磅
        setDataForm((prev) => ({
          ...prev,
          zhongG: value,
          zhongOz: calc.divide(value, 28.3495), // 1盎司=28.3495克
          zhongP: calc.divide(value, 453.592) // 1磅=453.592克
        }))
        break
      case "fba1":
        // FBA美元变化，更新FBA人民币
        setDataForm((prev) => ({
          ...prev,
          fba1: value,
          fba2: calc.multiply(value, prev.huilv)
        }))
        break
      case "dingjia1":
        // 定价美元变化，更新定价人民币
        setDataForm((prev) => ({
          ...prev,
          dingjia1: value,
          dingjia2: calc.multiply(value, prev.huilv),
          guanggao: calc.multiply(
            calc.multiply(value, prev.huilv),
            calc.divide(prev.guanggaolv, 100)
          ),
          tuihuo: calc.multiply(
            calc.multiply(value, prev.huilv),
            calc.divide(prev.tuihuolv, 100)
          ),
          cangchu: calc.multiply(
            calc.multiply(value, prev.huilv),
            calc.divide(prev.cangchulv, 100)
          ),
          yongjin: calc.multiply(
            calc.multiply(value, prev.huilv),
            calc.divide(prev.yongjinlv, 100)
          )
        }))
        break
      case "huilv":
        // 汇率变化，更新FBA人民币和定价人民币
        setDataForm((prev) => ({
          ...prev,
          huilv: value
        }))
        handleInputChange("fba1", dataForm.fba1)
        handleInputChange("dingjia1", dataForm.dingjia1)
        break
      case "guanggaolv":
        // 广告率变化，更新广告费用
        setDataForm((prev) => ({
          ...prev,
          guanggaolv: value,
          guanggao: calc.multiply(prev.dingjia2, calc.divide(value, 100))
        }))
        break
      case "tuihuolv":
        // 退货率变化，更新退货费用
        setDataForm((prev) => ({
          ...prev,
          tuihuolv: value,
          tuihuo: calc.multiply(prev.dingjia2, calc.divide(value, 100))
        }))
        break
      case "cangchulv":
        // 仓储率变化，更新仓储费用
        setDataForm((prev) => ({
          ...prev,
          cangchulv: value,
          cangchu: calc.multiply(prev.dingjia2, calc.divide(value, 100))
        }))
        break
      case "yongjinlv":
        // 佣金率变化，更新佣金费用
        setDataForm((prev) => ({
          ...prev,
          yongjinlv: value,
          yongjin: calc.multiply(prev.dingjia2, calc.divide(value, 100))
        }))
        break

      default:
        setDataForm((prev) => ({
          ...prev,
          [fieldName]: value
        }))
    }
  }

  // 计算毛利
  function onCompute() {
    const {
      caigou,
      fba2,
      dingjia2,
      toucheng,
      guanggao,
      tuihuo,
      cangchu,
      yongjin
    } = dataForm
    const maochengben = calc.add(caigou, fba2, toucheng, yongjin)
    const jingchengben = calc.add(maochengben, guanggao, tuihuo, cangchu)

    const maoli = calc.subtract(dingjia2, maochengben)
    const jingli = calc.subtract(dingjia2, jingchengben)

    setDataForm((prev) => ({
      ...prev,
      maochengben,
      jingchengben,
      maoli,
      maolilv: calc.chain(maoli).divide(dingjia2).multiply(100).round(2),
      jingli,
      jinglilv: calc.chain(jingli).divide(dingjia2).multiply(100).round(2)
    }))
  }

  // 获取页面信息
  async function onGetDomData() {
    try {
      // 获取当前活动标签页
      // @ts-ignore
      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
      })
      console.log(tab)

      if (tab?.id) {
        // @ts-ignore{
        const response = await chrome.tabs.sendMessage(tab.id, {
          action: "getDomData",
          data: {
            // message: "Hello from Popup!",
            popupTime: new Date().toISOString()
          }
        })
        console.info(response?.data || "无响应")
        const { chang, kuan, gao, zhong, shoujia, fba } = response?.data
        handleInputChange("fba1", fba)
        handleInputChange("dingjia1", shoujia)
        handleInputChange("chang1", chang)
        handleInputChange("kuan1", kuan)
        handleInputChange("gao1", gao)
        handleInputChange("zhongP", zhong)
      }
    } catch (error) {
      console.error("发送到 Content Script 失败:", error)
    }
  }

  const [isShowFBACalcArea, setIsShowFBACalcArea] = useState(false)

  const [fbaState, setFbaState] = useState({
    size: "",
    price: 0
  })
  function onCalculateFBA() {
    const { price, size } = getFBA(dataForm)
    setFbaState({
      price,
      size
    })
  }

  function onSetFba() {
    handleInputChange("fba1", fbaState.price)
  }

  return (
    <div className="main">
      {isShowFBACalcArea && (
        <>
          <Row gutter={[8, 8]}>
            <Col span={3}>
              <h4 className="center h-full">长</h4>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="英制"
                value={dataForm.chang1}
                onChange={(val) => handleInputChange("chang1", val)}
                addonAfter="inch"></InputNumber>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="公制"
                value={dataForm.chang2}
                onChange={(val) => handleInputChange("chang2", val)}
                addonAfter="cm"></InputNumber>
            </Col>
            <Col span={3}>
              <h4 className="center h-full">宽</h4>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="英制"
                value={dataForm.kuan1}
                onChange={(val) => handleInputChange("kuan1", val)}
                addonAfter="inch"></InputNumber>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="公制"
                value={dataForm.kuan2}
                onChange={(val) => handleInputChange("kuan2", val)}
                addonAfter="cm"></InputNumber>
            </Col>
            <Col span={3}>
              <h4 className="center h-full">高</h4>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="英制"
                value={dataForm.gao1}
                onChange={(val) => handleInputChange("gao1", val)}
                addonAfter="inch"></InputNumber>
            </Col>
            <Col span={10}>
              <InputNumber
                placeholder="公制"
                value={dataForm.gao2}
                onChange={(val) => handleInputChange("gao2", val)}
                addonAfter="cm"></InputNumber>
            </Col>
          </Row>
          <Row className="mt-8" gutter={[8, 8]}>
            <Col span={3}>
              <h4 className="center h-full">重量</h4>
            </Col>
            <Col span={7}>
              <InputNumber
                placeholder="英制盎司"
                value={dataForm.zhongOz}
                onChange={(val) => handleInputChange("zhongOz", val)}
                addonAfter="oz"></InputNumber>
            </Col>
            <Col span={7}>
              <InputNumber
                placeholder="英制磅"
                value={dataForm.zhongP}
                onChange={(val) => handleInputChange("zhongP", val)}
                addonAfter="p"></InputNumber>
            </Col>
            <Col span={7}>
              <InputNumber
                placeholder="公制"
                value={dataForm.zhongG}
                onChange={(val) => handleInputChange("zhongG", val)}
                addonAfter="g"></InputNumber>
            </Col>
            <Col span={3}>
              <h4 className="center h-full">体积重</h4>
            </Col>
            <Col span={7} className="center">
              {calc.multiply(dataForm.tijizhong1, 16)}oz
            </Col>
            <Col span={7} className="center">
              {dataForm.tijizhong1}p
            </Col>
            <Col span={7} className="center">
              {dataForm.tijizhong2}kg
            </Col>
          </Row>
          <Row className="mt-16" gutter={[8, 8]}>
            <Col span={8}>
              重量：{dataForm.zhongOz}oz / {dataForm.zhongP}p
            </Col>
            <Col span={8}>计费等级：{fbaState.size}</Col>
            <Col span={8}>FBA费用：${fbaState.price}</Col>
          </Row>
          <div className="mt-16 mb-16 flex-around">
            <Button type="primary" onClick={onCalculateFBA}>
              计算FBA
            </Button>
            <Button type="primary" onClick={onSetFba}>
              应用数据
            </Button>
            <Button type="primary" onClick={() => setIsShowFBACalcArea(false)}>
              隐藏
            </Button>
          </div>
        </>
      )}

      <Row gutter={[8, 8]} className="mt-8">
        <Col span={2}>
          <h4 className="center h-full">采购价</h4>
        </Col>
        <Col span={10}>
          <InputNumber
            className="w-full"
            placeholder="采购价"
            value={dataForm.caigou}
            onChange={(val) => handleInputChange("caigou", val)}
            addonBefore="￥"></InputNumber>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">FBA</h4>
        </Col>
        <Col span={4}>
          <InputNumber
            placeholder="FBA费用"
            value={dataForm.fba1}
            onChange={(val) => handleInputChange("fba1", val)}
            addonBefore="$"></InputNumber>
        </Col>
        <Col span={3} className="center">
          <span>￥{dataForm.fba2}</span>
        </Col>
        <Col
          span={3}
          className="center"
          onClick={() => setIsShowFBACalcArea(!isShowFBACalcArea)}>
          <a>计算</a>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">定价</h4>
        </Col>
        <Col span={5}>
          <InputNumber
            className="w-full"
            placeholder="定价"
            value={dataForm.dingjia1}
            onChange={(val) => handleInputChange("dingjia1", val)}
            addonBefore="$"></InputNumber>
        </Col>
        <Col span={5} className="center">
          <span>￥{dataForm.dingjia2}</span>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">汇率</h4>
        </Col>
        <Col span={10}>
          <InputNumber
            className="w-full"
            placeholder="汇率"
            value={dataForm.huilv}
            onChange={(val) => handleInputChange("huilv", val)}></InputNumber>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">头程</h4>
        </Col>
        <Col span={10}>
          <InputNumber
            className="w-full"
            placeholder="头程"
            value={dataForm.toucheng}
            onChange={(val) => handleInputChange("toucheng", val)}
            addonBefore="￥"></InputNumber>
        </Col>
      </Row>
      <Row gutter={[8, 8]} className="mt-8">
        <Col span={2}>
          <h4 className="center h-full">广告</h4>
        </Col>
        <Col span={5}>
          <InputNumber
            placeholder="广告率"
            value={dataForm.guanggaolv}
            onChange={(val) => handleInputChange("guanggaolv", val)}
            addonAfter="%"></InputNumber>
        </Col>
        <Col span={5} className="center">
          <span>￥{dataForm.guanggao}</span>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">退货</h4>
        </Col>
        <Col span={5}>
          <InputNumber
            placeholder="退货率"
            value={dataForm.tuihuolv}
            onChange={(val) => handleInputChange("tuihuolv", val)}
            addonAfter="%"></InputNumber>
        </Col>
        <Col span={5} className="center">
          <span>￥{dataForm.tuihuo}</span>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">仓储</h4>
        </Col>
        <Col span={5}>
          <InputNumber
            placeholder="仓储率"
            value={dataForm.cangchulv}
            onChange={(val) => handleInputChange("cangchulv", val)}
            addonAfter="%"></InputNumber>
        </Col>
        <Col span={5} className="center">
          <span>￥{dataForm.cangchu}</span>
        </Col>
        <Col span={2}>
          <h4 className="center h-full">佣金</h4>
        </Col>
        <Col span={5}>
          <InputNumber
            placeholder="佣金率"
            value={dataForm.yongjinlv}
            onChange={(val) => handleInputChange("yongjinlv", val)}
            addonAfter="%"></InputNumber>
        </Col>
        <Col span={5} className="center">
          <span>￥{dataForm.yongjin}</span>
        </Col>
      </Row>
      <Row gutter={[8, 8]} className="mt-8">
        <Col span={2}>
          <h4 className="center h-full">毛成本</h4>
        </Col>
        <Col span={6} className="center">
          ￥{dataForm.maochengben}
        </Col>
        <Col span={2}>
          <h4 className="center h-full">毛利</h4>
        </Col>
        <Col span={6} className="center">
          ￥{dataForm.maoli}
        </Col>
        <Col span={2}>
          <h4 className="center h-full">毛利率</h4>
        </Col>
        <Col span={6} className="center">
          {dataForm.maolilv}%
        </Col>
        <Col span={2}>
          <h4 className="center h-full">净成本</h4>
        </Col>
        <Col span={6} className="center">
          ￥{dataForm.jingchengben}
        </Col>
        <Col span={2}>
          <h4 className="center h-full">净利</h4>
        </Col>
        <Col span={6} className="center">
          ￥{dataForm.jingli}
        </Col>
        <Col span={2}>
          <h4 className="center h-full">净利率</h4>
        </Col>
        <Col span={6} className="center">
          {dataForm.jinglilv}%
        </Col>
      </Row>
      <div className="mt-16 flex-around">
        <Button type="primary" onClick={onGetDomData}>
          获取数据
        </Button>
        <Button type="primary" onClick={onCompute}>
          计算
        </Button>
      </div>
    </div>
  )
}

export default IndexPopup
